package com.gitee.ywj1352.算法.真实;

import com.gitee.ywj1352.算法.week02.TreeNode;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class 二叉树遍历 {
    public List<Integer> postorderTraversal(TreeNode root) {
        Stack<TreeNode> stack = new Stack<TreeNode>();
        List<Integer> res = new ArrayList<Integer>();
        TreeNode pre  = null;
        while(root != null || !stack.isEmpty()){
            while(root!=null){
                stack.push(root);
                root = root.left;
            }
            //看当前
            root = stack.peek();
            //当前的 右边要是==null 或者 右边以及被我访问过了 则add 记录 pre 并且 放空 自己  root== null;
            if(root.right == null || root.right == pre){
                res.add(root.val);
                stack.pop();
                pre = root;
                root = null;
            }else{
                root = root.right;
            }
        }
        return res;
    }

    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();
        Stack<TreeNode> stack = new Stack<TreeNode>();
        while(root !=null || !stack.isEmpty()){
            while(root!=null){
                stack.push(root);
                root = root.left;
            }
            TreeNode r = stack.pop();
            res.add(r.val);
            root = r.right;
        }
        return res;
    }


    public static List<Integer> preOrder(TreeNode root){
        List<Integer> list = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while(cur!=null || !stack.isEmpty()){
            //一直往左压入栈
            while(cur!=null){
                list.add(cur.val);
                stack.push(cur);
                cur = cur.left;
            }
            cur = stack.pop();
            cur = cur.right;
        }
        return list;
    }

}
